package com.zjitc.token;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.junit.Test;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/2 13:53
 * @description:
 */
public class Cache {

  private Map<String, Token> tokens = new ConcurrentHashMap<>();

  public void add(String username, String uuid) {
    tokens.put(username, new Token(uuid, LocalDateTime.now()));
  }

  public Token get(String username) {
    return tokens.get(username);
  }

  public Set<Entry<String, Token>> getAllTokens() {
    return tokens.entrySet();
  }

  public static void main(String[] args) {
    Cache cache = new Cache();
    cache.add("a", "a");
    cache.add("b", "b");
    cache.add("c", "c");
    //ExecutorService executor = Executors.newSingleThreadExecutor();
    ScheduledExecutorService service = Executors.newScheduledThreadPool(1);
    System.out.println("当前时间：" + LocalDateTime.now());
    service.scheduleAtFixedRate(() -> {
      System.out.println("第一次运行时间" + LocalDateTime.now());
      while (true) {
        /*try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.println(LocalDateTime.now());
        */
        /*检查在cache中 是否有数据过期 如果有 将其打印*/
        Set<Entry<String, Token>> sets = cache.getAllTokens();
        for (Entry<String, Token> entry : sets) {
          String key = entry.getKey();
          Token token = entry.getValue();
          LocalDateTime cteateTime = token.getCreateTime();
          LocalDateTime nowTime = LocalDateTime.now();

          //如何计算时间
          Duration between = Duration.between(cteateTime, nowTime);
          if (between.abs().toMillis() > 5000) {
            System.out.println(token.getUuid());
          }
        }
      }
    }, 1000, 1000, TimeUnit.MILLISECONDS);
    Scanner scanner = new Scanner(System.in);
    scanner.next();

  }

  @Test
  public void druing() {
    LocalDateTime t1 = LocalDateTime.now();
    try {
      Thread.sleep(1020);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    LocalDateTime t2 = LocalDateTime.now();

    System.out.println(t1);
    System.out.println(t2);

    //怎么对t1和t2求时间间隔
    Duration between = Duration.between(t1, t2);
    System.out.println(between.abs().toMillis());
  }

}
